﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;


namespace WindowsFormsApp2.类
{
    public class Socketconnect
    {
      
        public int ConnectionState=0;
        //0，未连接，1已连接，2启动，3暂停
        public string exmes = "";
        //异常消息
        public string controlIP = "127.0.0.1";
        public int port = 8008;
        public Socket robot_socket = null;
        private int DEFAULT_TIMEOUT = 125;
        //协议版本号

        public DataConfig outputdataC = new DataConfig();

      //  public data_package Curstate = new data_package();
        private byte[] bufffs = new byte[4096];
        public string receivestring = "";

        public int receNum= 0;
        public Boolean Receflag = false;   //接受到数据
        public Boolean stopRecvFlag = false;

        private SocketAsyncEventArgs readargs = new SocketAsyncEventArgs();

        public bool  connect()
        {

            try
            {
                if (robot_socket != null)
                {
                    return false ;
                }
                robot_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                robot_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                // RDTE_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, true);
                robot_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
                //不写停止时间
                robot_socket.ReceiveTimeout = DEFAULT_TIMEOUT;
               
                //注册回调
                readargs = new SocketAsyncEventArgs();
                readargs.SetBuffer(bufffs, 0, 4096);
                readargs.Completed += onrecived;
                robot_socket.Connect(controlIP, port);
                robot_socket.ReceiveAsync(readargs);

                ConnectionState = 1 ;
                //开启接收数据线程，并具备自动重连功能
                return true ;
                //核对版本信息
            }
            catch (Exception ex)
            {
                robot_socket = null;
                exmes = ex.Message;
                return false ;
            }

        }
        //发送字符串函数
        public void SendStr(string strBytes)
        {
            try
            {
                
                byte[] BData = StrToAscii(strBytes);
                robot_socket.Send(BData);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        //发送字节数组函数
        public void SendBytes(byte[] Bytes)
        {
            try
            {
                robot_socket.Send(Bytes);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        

        public byte[] StrToAscii(string hexString)
        {
            try
            {

                byte[] returnBytes = Encoding.Default.GetBytes(hexString);

                return returnBytes;
            }
            catch (Exception ex)
            {
                byte[] returnBytes = { };
                return returnBytes;
            }
        }
        /// 将16进制字符串转为BYTE[]型
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public byte[] StrToHexByte(string hexString)
        {
            try
            {
                hexString = hexString.Replace(" ", "");
                if ((hexString.Length % 2) != 0)
                    hexString = "0" + hexString;
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }
            catch (Exception ex)
            {
                byte[] returnBytes = { };
                return returnBytes;
            }

        }

        private void onrecived(object sender, SocketAsyncEventArgs e)
        {
            //保持连贯性
            if (robot_socket != null)
            {
                
                int n = e.BytesTransferred;
                byte[] buf = e.Buffer.Take(n).ToArray();
                //byte[] numbyte = { buf[3], buf[4] };




                try
                {

                    if (n >= 3)
                    {
                        //解码

                        if (n ==9)
                        {
                            byte[] numbyte = { buf[3], buf[4], buf[5], buf[6] };

                            // 使用BitConverter.ToInt32方法将字节数组转换为整数
                            int result = BitConverter.ToInt32(numbyte, 0);
                            receNum = result;

                        }
                        receivestring = Encoding.Default.GetString(buf);
                        //使用该变量对返回的字符进行监视
                        // receivestring = Convert.ToString(System.Text.Encoding.ASCII.GetString(buf));


                    }
                    else
                    {

                    }
                    if (robot_socket != null)
                    {
                    robot_socket.ReceiveAsync(readargs);
                    }
                    //处理超时异常
                }
                catch (Exception ex)
                {

                    if (robot_socket != null)
                    {
                        robot_socket.ReceiveAsync(readargs);
                    }
                }
               
      
                Receflag = true;
            }         
            else
            {
                Receflag = false;
            }
        }


        public void disconnect()
        {
            if(robot_socket != null)
            {
                robot_socket.Disconnect(true);
                robot_socket.Close();
                robot_socket = null;
                Thread.Sleep(100);
            }
            ConnectionState= 0;
        }

        /// <summary>
        /// 读取RDTE配置文件
        /// </summary>



        //这个地方采用一直等待的方式
        Stopwatch cummtime = new Stopwatch();

        
    }



    //输入对象的应用
    public class InputObjbas
    {
       public int recipeID{get;set;}
       
       public virtual byte[] Pack()
        {
            return null;
        }
       
    }

    public class Watchdog:InputObjbas
    {
        public int input_int_register_0{get;set;}
        public static byte[] Pack(Watchdog obj)
        {
            byte[] id =new byte[1];
            id[0] = (byte)obj.recipeID;
            return id.Concat(BitConverter.GetBytes(obj.input_int_register_0).Reverse().ToArray())
                .ToArray();
        }

    }
    public class DataConfig
    {
        //四种关键类型
        public int id;
        public List<string> types;

        public static DataConfig Unpack_recipe(byte[] buf)
        {
            DataConfig resultobj = new DataConfig();
            resultobj.id = (int)buf[0];
            // Decoder temp = new Decoder();
            resultobj.types = Encoding.UTF8.GetString(buf.Skip(1).Take(buf.Length - 1).ToArray()).Split(',').ToList();
            return resultobj;
        }

    }

}
